package org.misalen.web.service.sms.impl;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.misalen.web.service.sms.AliSms;
import org.misalen.web.service.sms.info.AliInfoType;
import org.springframework.stereotype.Service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import net.sf.json.JSONObject;

@Service
public class AliSmsImpl implements AliSms {
	IAcsClient acsClient;
	static Properties p = new Properties();
	static {
		InputStream in = AliSmsImpl.class.getClassLoader().getResourceAsStream("pro.properties");
		try {
			p.load(in);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	public AliSmsImpl() {
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");
		IClientProfile profile = DefaultProfile.getProfile(p.getProperty("sms.ali.endpoint"),
				p.getProperty("sms.ali.accessKeyId"), p.getProperty("sms.ali.accessKeySecret"));
		try {
			DefaultProfile.addEndpoint(p.getProperty("sms.ali.endpoint"), p.getProperty("sms.ali.endpoint"),
					p.getProperty("sms.ali.product"), p.getProperty("sms.ali.domain"));
		} catch (ClientException e) {
			e.printStackTrace();
		}
		acsClient = new DefaultAcsClient(profile);
	}

	@Override
	public boolean send(String mobile, AliInfoType infoType, JSONObject strings) {
		SendSmsRequest request = new SendSmsRequest();
		request.setPhoneNumbers(mobile);
		request.setSignName(p.getProperty("sms.ali.signName"));
		request.setTemplateCode(p.getProperty(infoType.templateId));
		request.setTemplateParam(strings.toString());
		try {
			SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);
			return sendSmsResponse.getCode().equals("OK");
		} catch (ClientException e) {
			e.printStackTrace();
		}
		return false;
	}
}
